const audio = require("../models/audio")
const fs = require('fs')
// const bodyParser = require('body-parser')

var express = require('express');
var router = express.Router();

const path = require('path')

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            // console.log('eee',fields.audio)
            let today = new Date(fields.today).toLocaleDateString()
            let dir_path = `${ path.resolve(__dirname, '../../static/audio') }\/${ today }`
            if(!fs.existsSync(dir_path)){
                fs.mkdirSync(dir_path)
            }
            let filename = fields.filename.substring(0, fields.filename.lastIndexOf('-')),
                file_path = `${dir_path}\/${filename}`
            if(!fs.existsSync(file_path)){
                fs.mkdirSync(file_path)
            }
            let chunk_dir = `${file_path}\/${fields.filename}.txt`
            // let chunk = decodeURIComponent(fields.audio.replace(/^data:application\/\w+;base64,/, ""))
            // chunk = Buffer.from(chunk, 'base64')
            let chunk = fields.audio
            fs.writeFileSync(chunk_dir, chunk)
            // let readStream = fs.createReadStream(audio.path),
            //     writeStream = fs.createWriteStream(`${file_path}\/${fields.filename}.txt`)
            // readStream.pipe(writeStream)
            // readStream.on('end', () => {
            //     fs.unlinkSync(audio.path);
            // })
            res.json({ 'state': true })
            
        }

    });

});

module.exports = router;